<template>
  <div>
    <el-container>
      <el-header>
        <h2>实时聊天与好友管理</h2>
      </el-header>
      <el-main>
        <div class="friend-management">
          <el-input v-model="newFriendId" placeholder="输入好友ID" style="margin-bottom: 10px;"></el-input>
          <el-button type="primary" @click="addFriend">添加好友</el-button>

          <el-table :data="friendsList" style="margin-top: 20px;">
            <el-table-column prop="userId" label="好友ID"></el-table-column>
            <el-table-column prop="userName" label="好友名称"></el-table-column>
            <el-table-column>
              <template #default="scope">
                <el-button @click="selectFriend(scope.row)" type="primary">选择</el-button>
                <el-button @click="deleteFriend(scope.row.userId)" type="danger">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div class="chat-section" v-if="selectedFriend" style="margin-top: 40px;">
          <h3>与 {{ selectedFriend.userName }} 聊天</h3>
          <el-table :data="messagesList" style="margin-bottom: 20px;">
            <el-table-column prop="senderName" label="发送者"></el-table-column>
            <el-table-column prop="content" label="消息内容"></el-table-column>
            <el-table-column prop="timestamp" label="时间戳"></el-table-column>
          </el-table>

          <el-input v-model="messageContent" placeholder="输入消息内容" style="margin-bottom: 10px;"></el-input>
          <el-button type="primary" @click="sendMessage">发送消息</el-button>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import axios from 'axios';
import WebSocketService from '../../services/websocketService'; // 调整路径根据项目结构

export default {
  data() {
    return {
      friendsList: [],
      newFriendId: '',
      messageContent: '',
      messagesList: [],
      selectedFriend: null,
      userId: 1, // 假设当前登录用户ID是1，实际情况需动态获取
    };
  },
  created() {
    this.getFriends();
    this.initializeWebSocket();
  },
  methods: {
    async getFriends() {
      try {
        const response = await axios.get(`http://localhost:8003/repair/friends/list`, {
          params: { userId: this.userId }
        });
        this.friendsList = response.data;
      } catch (error) {
        console.error('获取好友列表失败:', error.response ? error.response.data : error.message);
        this.$message.error('获取好友列表失败，请检查控制台');
      }
    },
    async addFriend() {
      try {
        const response = await axios.post(`http://localhost:8003/repair/friends/add`, null, {
          params: { userId: this.userId, friendId: this.newFriendId }
        });
        this.$message.success(response.data);
        this.getFriends();
        this.newFriendId = ''; // 清空输入框
      } catch (error) {
        console.error('添加好友失败:', error);
      }
    },
    async deleteFriend(friendId) {
      try {
        const response = await axios.delete(`http://localhost:8003/repair/friends/delete`, {
          params: { userId: this.userId, friendId }
        });
        this.$message.success(response.data);
        this.getFriends();
      } catch (error) {
        console.error('删除好友失败:', error);
      }
    },
    selectFriend(friend) {
      this.selectedFriend = friend;
      this.getMessages(); // 获取与选择好友的聊天记录
    },
    async getMessages() {
      if (this.selectedFriend) {
        try {
          const response = await axios.get(`http://localhost:8003/repair/messages/list`, {
            params: {
              senderId: this.userId,
              receiverId: this.selectedFriend.userId
            }
          });
          this.messagesList = response.data;
        } catch (error) {
          console.error('获取聊天记录失败:', error.response ? error.response.data : error.message);
          this.$message.error('获取聊天记录失败，请检查控制台');
        }
      }
    },
    sendMessage() {
      if (this.messageContent.trim() && this.selectedFriend) {
        const message = {
          senderId: this.userId,
          receiverId: this.selectedFriend.userId,
          content: this.messageContent,
          timestamp: new Date().toISOString()
        };

        WebSocketService.sendMessage(message);
        this.messageContent = '';
      }
    },
    initializeWebSocket() {
      WebSocketService.connect('ws://localhost:8003/ws/chat');
      WebSocketService.onOpen(() => {
        console.log('WebSocket连接已建立');
      });
      WebSocketService.onMessage((message) => {
        if (message.senderId === this.selectedFriend?.userId || message.receiverId === this.selectedFriend?.userId) {
          this.messagesList.push(message);
        }
      });
      WebSocketService.onClose(() => {
        console.log('WebSocket连接已关闭');
      });
    }
  },
  beforeDestroy() {
    WebSocketService.close();
  }
};
</script>

<style scoped>
.friend-management {
  margin-bottom: 40px;
}

.chat-section {
  margin-top: 20px;
}
</style>
